package com.hmall.order.web.controller;

import com.hmall.domain.constant.MqConstant;
import com.hmall.domain.dto.OrderPayDto;
import com.hmall.domain.pojo.Order;
import com.hmall.order.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

/**
 * 订单web层控制器
 *
 * @author xiaojiangshi
 */
@Slf4j
@RestController
@RequestMapping("order")
public class OrderController {

    @Autowired
    private IOrderService orderService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 根据id查询订单
     *
     * @param orderId 订单id
     * @return 订单数据
     */
    @GetMapping("{id}")
    public Order queryOrderById(@PathVariable("id") Long orderId) {
        return orderService.getById(orderId);
    }

    /**
     * 根据条件提交订单
     *
     * @param orderPayDto 订单信息
     * @return 订单id
     */
    @PostMapping
    public Long commitOrder(@RequestBody OrderPayDto orderPayDto) {
        log.info("提交订单的信息：[{}]", orderPayDto.toString());
        //获得orderId
        Long orderId = orderService.commitOrder(orderPayDto);
        //构建发送信息
        Message message = MessageBuilder.withBody(orderId.toString().getBytes(StandardCharsets.UTF_8))
                .setExpiration("10000").build();
        //构建消息id，需要封装到CorrelationData对象中
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
        //发送消息
        rabbitTemplate.convertAndSend(MqConstant.ORDER_COMMIT_QUEUE, MqConstant.ITEM_DELETE_ROUT, message, correlationData);
        return orderId;
    }
}
